package j41;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chengshuai
 * @date 2021/4/15 13:24
 */
public class ProduceConsumeLock {

    private int number = 0;
    private Lock lock = new ReentrantLock();

    //条件
    private Condition condition = lock.newCondition();

    public void increment() {
        lock.lock();
        try {
            //1、判断
            while (number != 0) {
                //等待，不能生产
                condition.await();
            }
            //2、干活
            number++;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            //3、通知唤醒
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() {
        lock.lock();
        //1、判断
        try {
            while (number == 0) {
                //等待，不能消费
                condition.await();
            }
            //2、干活
            number--;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            //3、通知唤醒
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ProduceConsumeLock produceConsume = new ProduceConsumeLock();
        new Thread(() -> {
            for (int i = 0; i < 2; i++) {
                produceConsume.increment();
            }
        },"AA").start();

        new Thread(() -> {
            for (int i = 0; i < 2; i++) {
                produceConsume.decrement();
            }
        },"BB").start();

        new Thread(() -> {
            for (int i = 0; i < 2; i++) {
                produceConsume.increment();
            }
        },"CC").start();

        new Thread(() -> {
            for (int i = 0; i < 2; i++) {
                produceConsume.decrement();
            }
        },"DD").start();
    }
}
